// pages/browsing/browsing.js
// 引入封装好的请求数据的js文件
const util = require('../../request/index')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    browsingList: [],
    userId: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  onShow: function () {
    this.setData({
      userId: wx.getStorageSync('userInfo').userId
    })
    this.getBrowsingList();

  },
  async getBrowsingList() {
    var browsingList = wx.getStorageSync('browsingList');
    if (browsingList) {
      this.setData({
        browsingList
      })
    } else {
      util.request_get('/web/user/browsing', {
        userId: this.data.userId
      }).then((res) => {
        if (res.code == 200) {
          // 下次报错的话  先看看你响应结果有没有成功
          console.log(res); // 这里不是打印了吗 
          this.setData({
            browsingList: res.data
          })
          // 添加字段
          this.data.browsingList.forEach((v, i) => {
            if (v.goodsList.length > 0) {
              v.goodsList.forEach((v, j) => {
                var isShow = "browsingList[" + i + "].goodsList[" + j + "].isShowDelete"
                this.setData({
                  [isShow]: false
                })
              })
            }
          })
          wx.setStorageSync('browsingList', this.data.browsingList)
        }
      })
    }
  },
  showDeleteBtn(e) {
    // 传入id 修改
    var goodsId = e.currentTarget.dataset.goodsid;
    var browsingList = this.data.browsingList;
    browsingList.forEach((v, i) => {
      if (v.goodsList.length > 0) {
        v.goodsList.forEach((v1, j) => {
          if (v1.goodsId == goodsId) {
            v1.isShowDelete = true
          } else {
            v1.isShowDelete = false
          }
        })
      }
    })
    this.setData({
      browsingList
    })
  },
  //删除
  shanchu(e) {
    var that = this
    //获得绑定的商品id
    var goodsId = e.currentTarget.dataset.goodsid
    console.log(e);
    util.request_json_post('/web/user/browsing/delete', {
      userId: that.data.userId,
      goodsId: goodsId
    }).then((res) => {
      if (res.code === 200) {
        wx.showToast({
          title: '删除成功',
        })
      }
    })
    wx.removeStorageSync('browsingList')
    var browsingList = this.data.browsingList;
    browsingList.forEach((v, i) => {
      if (v.goodsList.length > 0) {
        v.goodsList.forEach((v1, j) => {
          if (v1.goodsId == goodsId) {
          v.goodsList.splice(j,1)
          }
          if (v.goodsList.length == 0) {
            browsingList.splice(i, 1)
          }
        })
      }
    })
    this.setData({
      browsingList
    })
    wx.removeStorageSync('myInfo')
  }
})